<template>
  <view class="page-container">
    <!-- 固定头部区域 -->
    <view class="fixed-header" :style="{ paddingTop: statusBarHeight + 'px' }">
      <!-- 导航栏 -->
      <view class="nav-bar">
        <view class="title">我的智能体</view>
      </view>
    </view>

    <!-- 可滚动内容区域 -->
    <scroll-view
      class="scrollable-content" 
      :style="{ top: `calc(${statusBarHeight}px + 88rpx)` }"
      scroll-y 
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="refresh"
    >
      <!-- 空状态 - 修改后的版本 -->
      <view v-if="deviceList.length === 0" class="empty-state">
        <image src="" mode="aspectFit" class="empty-image" />
        
        <!-- 游客模式显示登录提示 -->
        <view v-if="userStore.isGuestMode" class="login-container">
          <view class="login-prompt">登录后享受更多功能</view>
          <button class="login-button" @tap="goToLogin">立即登录</button>
        </view>
        
        <!-- 登录用户显示添加智能体提示 -->
        <template v-else>
          <view class="empty-text">还没有添加智能体</view>
          <view class="empty-action" @tap="goToDiscover">去发现页添加</view>
        </template>
      </view>

      <!-- AI列表 -->
      <view v-else class="device-list">
        <view
          :class="[
            'device-item',
            item.is_premium || item.isPremium ? 'premium-item' : '',
            swipedItemId === item.id ? 'swiped' : ''
          ]"
          v-for="item in deviceList" 
          :key="item.id"
          @tap="(e) => startChat(item, e)"
          @touchstart="handleTouchStart($event, item.id)"
          @touchend="handleTouchEnd($event, item.id)"
          :data-device-id="item.id"
        >
          <!-- 高级模型专属徽章 - 移动到卡片左上角 -->
          <view v-if="item.is_premium || item.isPremium" class="premium-badge">
            <text class="premium-icon">👑</text>
            <text class="premium-text">高级</text>
          </view>

          <image class="avatar" :src="item.icon || defaultAvatar" mode="aspectFill" />
          <view class="content">
            <view :class="['title', item.is_premium || item.isPremium ? 'premium-title' : '']">{{ item.name }}</view>
            <view :class="['desc', item.is_premium || item.isPremium ? 'premium-desc' : '']">{{ item.description }}</view>
            <view class="chat-info">
              <view :class="['last-chat', item.is_premium || item.isPremium ? 'premium-info' : '']">{{ item.lastMessage || '开始对话' }}</view>
              <view class="time" v-if="item.lastMessageTime">{{ formatTime(item.lastMessageTime) }}</view>
            </view>
          </view>
          <view class="action-buttons" v-if="swipedItemId === item.id" @tap.stop="uncollectDevice(item.id)">
            <view class="uncollect-btn">取消收藏</view>
          </view>
        </view>
      </view>
    </scroll-view>
    
    <!-- 固定底部导航 -->
    <view class="fixed-footer">
      <TabBar :current-tab="0" />
    </view>
  </view>
</template>

<script setup>
// index.vue的<script setup>部分
import { ref, onMounted, onUnmounted } from 'vue'
import { useDeviceStore, useUserStore } from '@/stores'
import { system } from '@/utils'
import TabBar from '@/components/TabBar/TabBar.vue'

// 用户状态
const userStore = useUserStore()

// 滑动相关状态
const touchStartX = ref(0)
const touchEndX = ref(0)
const swipedItemId = ref(null)

const deviceStore = useDeviceStore()
const statusBarHeight = system.getStatusBarHeight()

// 默认头像
const defaultAvatar = '/static/images/default-avatar.png'

// 列表数据
const deviceList = ref([])
const loading = ref(false)
const refreshing = ref(false)
const currentPage = ref(1)
const pageSize = 10

// 设置路由变化监听
const setupRouteWatcher = () => {
  // 获取当前页面路由对象
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  
  if (currentPage) {
    // 手动监听页面显示事件
    const onShowHandler = () => {
      console.log('index页面显示，刷新数据');
      // 如果设备列表为空，则加载数据
      if (deviceList.value.length === 0) {
        loadData();
      } else {
        // 有数据时轻量刷新，确保列表不会重复加载
        refreshing.value = true;
        loadData().finally(() => {
          setTimeout(() => {
            refreshing.value = false;
          }, 300);
        });
      }
    };
    
    // 添加页面显示事件监听
    currentPage.onShow = function() {
      onShowHandler();
      // 保留原有的onShow逻辑，如果有的话
      if (this.$mp && this.$mp.page && this.$mp.page._onShow) {
        this.$mp.page._onShow();
      }
    };
  }
};

// 跳转登录页
const goToLogin = () => {
  uni.navigateTo({
    url: '/pages/login/account-login'
  })
}

// 取消收藏
const uncollectDevice = async (deviceId) => {
  try {
    await deviceStore.uncollectDevice(deviceId)
    // 更新列表
    deviceList.value = deviceList.value.filter(item => item.id !== deviceId)
    uni.showToast({
      title: '已取消收藏',
      icon: 'success'
    })
  } catch (error) {
    console.error('取消收藏失败:', error)
    uni.showToast({
      title: '取消收藏失败',
      icon: 'none'
    })
  }
}

// 处理滑动开始
const handleTouchStart = (e, deviceId) => {
  touchStartX.value = e.touches[0].clientX
}

// 处理滑动结束
const handleTouchEnd = (e, deviceId) => {
  touchEndX.value = e.changedTouches[0].clientX;
  const swipeDistance = touchStartX.value - touchEndX.value;
  // 只有左滑超过阈值才设置滑动状态
  if (swipeDistance > 50) {
    swipedItemId.value = deviceId;
  } else if (swipeDistance < -50) {
    // 右滑时重置滑动状态
    swipedItemId.value = null;
  } else if (Math.abs(swipeDistance) < 10) {
    // 如果几乎没有滑动，保持当前状态不变
    // 这样可以确保点击事件能正常触发
  } else {
    // 其他情况重置滑动状态
    swipedItemId.value = null;
  }
}

// 开始对话
const startChat = (device, e) => {
  // 如果当前有其他项目处于滑动状态，先重置它
  if (swipedItemId.value !== null && swipedItemId.value !== device.id) {
    swipedItemId.value = null; // Reset swiped item
    return;
  }
  
  // 如果当前项目处于滑动状态，点击时只重置滑动状态，不进行导航
  if (swipedItemId.value === device.id) {
    swipedItemId.value = null;
    return;
  }
  
  // 正常导航到聊天页面
  uni.navigateTo({
    url: `/pages/chat/chat?id=${device.id}`
  });

}

// 底部导航配置
const tabs = [{
    text: '对话',
    icon: 'icon-message'
  },
  {
    text: '发现',
    icon: 'icon-search'
  },
  {
    text: '我的',
    icon: 'icon-user'
  }
]
const currentTab = ref(0) // 当前在对话页

// 加载数据
const loadData = async () => {
  if (loading.value) return;
  loading.value = true;

  try {
    // 先检查本地缓存
    const cachedDevices = uni.getStorageSync('collectedDevices');
    
    if (cachedDevices && !refreshing.value) {
      console.log('使用缓存的收藏设备列表数据');
      deviceList.value = cachedDevices;
      loading.value = false;
      return;
    }
    
    console.log('开始加载收藏设备列表')
    // 从商店获取设备列表
    const result = await deviceStore.loadCollectedDevices();
    
    // 安全访问数据
    const devices = result?.data || [];
    
    // 映射必要属性并处理可能的缺失数据，包括会员字段
    deviceList.value = devices.map(device => ({
      id: device.id,
      name: device.name || '未命名智能体',
      description: device.description || '无描述',
      icon: device.avatar || device.icon || defaultAvatar,
      lastMessage: device.lastMessage || '',
      lastMessageTime: null, // 避免使用日期时间字段
      // 添加会员字段支持
      is_premium: device.is_premium || false,
      isPremium: device.isPremium || device.is_premium || false
    }));
    
    // 保存到缓存
    uni.setStorageSync('collectedDevices', deviceList.value);
    console.log('处理后的设备列表:', deviceList.value)
  } catch (error) {
    console.error('加载失败:', error)
    // 出错时显示空列表
    deviceList.value = [];
  } finally {
    loading.value = false;
    // 下拉刷新延长时间
    setTimeout(() => {
      refreshing.value = false;
    }, 1000);
  }
}

// 加载更多
const loadMore = () => {
  // 目前API不支持分页，已加载所有数据
  console.log('已加载所有设备')
}

// 刷新
const refresh = async () => {
  refreshing.value = true;
  // 强制从服务器加载最新数据
  await loadData();
  setTimeout(() => {
    refreshing.value = false;
  }, 1000);
}

// 去发现页
const goToDiscover = () => {
  uni.switchTab({
    url: '/pages/discover/discover'
  })
}

// 切换标签页
const switchTab = (index) => {
  const routes = [
    '/pages/index/index',
    '/pages/discover/discover',
    '/pages/my/my'
  ]
  uni.switchTab({
    url: routes[index]
  })
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date

  // 今天的消息只显示时间
  if (diff < 24 * 60 * 60 * 1000 && date.getDate() === now.getDate()) {
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  // 一周内的消息显示星期几
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    const days = ['日', '一', '二', '三', '四', '五', '六']
    return `星期${days[date.getDay()]}`
  }

  // 更早的消息显示完整日期
  return date.toLocaleDateString('zh-CN', {
    month: '2-digit',
    day: '2-digit'
  })
}

// 监听登录状态变化事件
const setupLoginListener = () => {
  uni.$on('loginStateChanged', (data) => {
    console.log('首页检测到登录状态变化，强制刷新数据');
    // 设置refreshing为true，强制从服务器获取最新数据
    refreshing.value = true;
    // 登录成功后清除缓存
    uni.removeStorageSync('collectedDevices');
    // 刷新收藏设备列表
    loadData().finally(() => {
      setTimeout(() => {
        refreshing.value = false;
      }, 500);
    });
  })
}

onMounted(() => {
  loadData();
  // 设置登录状态变化监听
  setupLoginListener();
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  uni.$off('loginStateChanged');
})
</script>

<style lang="scss">
.device-list {
  .device-item {
    position: relative;
    display: flex;
    padding: 20rpx;
    background: #fff;
    transition: transform 0.3s ease;
    
    &.swiped {
      transform: translateX(-140rpx);
    }

    // 高级徽章样式 - 只添加这部分
    .premium-badge {
      position: absolute;
      top: 8rpx;
      left: 8rpx;
      background: linear-gradient(135deg, #ffd700, #ffed4e);
      color: #8b4513;
      padding: 4rpx 10rpx;
      border-radius: 8rpx;
      font-size: 20rpx;
      font-weight: 600;
      display: flex;
      align-items: center;
      z-index: 10;
      box-shadow: 0 2rpx 8rpx rgba(255, 215, 0, 0.3);
      line-height: 1;
    
      .premium-icon {
        margin-right: 4rpx;
        font-size: 22rpx;
      }
    
      .premium-text {
        font-size: 20rpx;
      }
    }
    
    .action-buttons {
      position: absolute;
      right: -140rpx;
      top: 0;
      height: 100%;
      width: 140rpx;
      display: flex;
      align-items: center;
      z-index: 10;
      
      .uncollect-btn {
        width: 140rpx;
        height: 100%;
        background: #ff4d4f;
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}
@import '@/common/style/mixins.scss';

.page-container {
  width: 100vw;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
  background: #f8f9fa;
  z-index: 1;

  .fixed-header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
    background: #fff;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

    .nav-bar {
      height: 88rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0 30rpx;
      background: #fff;

      .title {
        font-size: 36rpx;
        font-weight: 600;
        color: #333;
        letter-spacing: 1rpx;
      }
    }
  }

  .scrollable-content {
    position: fixed;
    left: 0;
    right: 0;
    bottom: calc(110rpx + env(safe-area-inset-bottom));
    background: #f8f9fa;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    padding: 0;

    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding-top: 200rpx;

      .empty-image {
        width: 280rpx;
        height: 280rpx;
        margin-bottom: 30rpx;
      }

      .empty-text {
        font-size: 30rpx;
        color: #999;
        margin-bottom: 24rpx;
      }

      .empty-action {
        font-size: 28rpx;
        color: #5677fc;
        padding: 16rpx 36rpx;
        background: rgba(86, 119, 252, 0.1);
        border-radius: 32rpx;
        transition: all 0.3s ease;

        &:active {
          transform: scale(0.95);
          opacity: 0.9;
        }
      }
	  .login-container {
	      margin: 30rpx 0;
	      background-color: rgba(86, 119, 252, 0.05);
	      padding: 30rpx;
	      border-radius: 16rpx;
	      text-align: center;
	      width: 80%;
	      box-shadow: 0 4rpx 12rpx rgba(86, 119, 252, 0.1);
	      
	      .login-prompt {
	        font-size: 28rpx;
	        color: #666;
	        margin-bottom: 20rpx;
	      }
	      
	      .login-button {
	        background: #5677fc;
	        color: #fff;
	        font-size: 30rpx;
	        padding: 10rpx 0;
	        border-radius: 40rpx;
	        width: 70%;
	        margin: 0 auto;
	        line-height: 2;
	      }
	    }
    }

    .device-list {
      padding: 20rpx 0;
      
      .action-buttons {
        position: absolute;
        right: 0;
        top: 0;
        height: 100%;
        width: 140rpx;
        display: flex;
        align-items: center;
        z-index: 10;
        
        .uncollect-btn {
          background-color: #ff4d4f;
          color: #fff;
          width: 140rpx;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 28rpx;
        }
      }
      
      .device-list-item,
      .device-item {
        position: relative;
        overflow: hidden;
        display: flex;
        align-items: center;
        padding: 32rpx 24rpx;
        background: #fff;
        border-bottom: 1px solid #eee;
        margin-bottom: 20rpx;
        border-radius: 16rpx;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    
        .avatar {
          width: 88rpx;
          height: 88rpx;
          border-radius: 44rpx;
          margin-right: 24rpx;
          flex-shrink: 0;
        }
    
        .content {
          flex: 1;
          min-width: 0;
    
          .title {
            font-size: 32rpx;
            color: #333;
            margin-bottom: 12rpx;
            font-weight: 500;

            // 高级模型标题样式
            &.premium-title {
              color: #d4af37;
              font-weight: 700;
            }
          }
    
          .desc {
            font-size: 26rpx;
            color: #666;
            margin-bottom: 16rpx;
            @include text-ellipsis;

            // 高级模型描述样式
            &.premium-desc {
              color: #8b6914;
            }
          }
    
          .chat-info {
            display: flex;
            align-items: center;
            justify-content: space-between;
    
            .last-chat {
              font-size: 24rpx;
              color: #999;
              @include text-ellipsis;
              flex: 1;
              margin-right: 16rpx;

              // 高级模型聊天信息样式
              &.premium-info {
                color: #b8860b;
                font-weight: 500;
              }
            }
    
            .time {
              font-size: 24rpx;
              color: #999;
              flex-shrink: 0;
            }
          }
        }
        
        &:active {
          transform: scale(0.98);
          opacity: 0.95;
          box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
        }
    
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }

  .fixed-footer {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 100;
    background: #fff;
    padding-bottom: env(safe-area-inset-bottom);
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  }
}
</style>